<?php
//mysql_connect('localhost', 'gogoalsh_stock', 'admin#stock_all') or exit("0");
//mysql_select_db('gogoalsh_stock') or exit("0");
mysql_connect('localhost', 'root', '123456') or exit("0");;
mysql_select_db('kucun') or exit("0");
$args = array();
require_once '../library/App/config.php';
set_include_path('.' . PATH_SEPARATOR . _LIB_DIR_ . PATH_SEPARATOR . get_include_path());
include 'Zend/Loader/Autoloader.php';
$autoLoader = Zend_Loader_Autoloader::getInstance();

$zendlog = new Zend_Log();
$stream = @fopen('./logfile', 'a', false);
$writer = new Zend_Log_Writer_Stream($stream);
$zendlog->addWriter($writer);

//获取远程调用对方传过来的值
$arr = json_decode(stripslashes($_POST['d']), true);
if(!$arr){
	$arr = json_decode($_POST['d'], true);
}

//判断该订单是否存在
$check = mysql_fetch_array(mysql_query("select * from stock_log where order_id=".$arr['order_id']." and site='".$arr['site']."'"));

mysql_query("SET AUTOCOMMIT=0");
mysql_query("BEGIN");
$flag = 1;

foreach ($arr['data']['data'] as $k=>$v) {
	foreach ($v['sizeNum'] as $_k=>$_v) {
		$num = intval($_v[1]);
		if(count($_v)!=2 || empty($_v[0]) ||$num<1){
			unset($v[$_k]);
			continue;
		}
		
		if ($num == 0) {
			$flag = 0;		
		}
		
		if ($arr['flag'] == 'sub') {
			$re = mysql_query("update stock_value set value=value-" . $num . " where sku=\"" . trim($k) . "\" and size=\"" . trim($_v[0]) . "\"");
		} else {
			$re = mysql_query("update stock_value set value=value+" . $num . " where sku=\"" . trim($k) . "\" and size=\"" . trim($_v[0]) . "\"");
		}
		
		if (!$re) {
			$flag = 0;
		}
		
		if($flag==0){
			$information="size num occured null update stock_value set value=value-" . $num . " where sku=\"" . trim($k) . "\" and size=\"" . trim($_v[0]) . "\"";
			$zendlog->log($information, Zend_Log::ERR);//错误记录
		}
	}
	
	if(empty($v)){
		continue;
	}
	
	if($arr['flag'] == 'sub'){
		//向库存管理插入网站订单数据
		if($check!==false){
			$res = mysql_query("update stock_log set info_stock=\"". $arr['flag'] ."\" where order_id=\"". $arr['order_id'] ."\" and site=\"". $arr["site"] ."\"");
		}else{
			$res = mysql_query("insert into stock_log (site, sku, info, info_stock, order_id, product_name, unit_price, print_msg, total_amount, add_time) values (\"". $arr["site"] ."\", \"". $k ."\",\"" . addslashes(json_encode($v['sizeNum']))."\", \"".$arr['flag']."\", \"".$arr['order_id']."\", \"".$v['productName']."\", \"".$v['unitPrice']."\", \"".$v['printMesg']."\", \"".$v['totalAmount']."\", \"".date('Y-m-d H:i:s', time())."\")");
		}
		
		if (!$res) {
			$flag = 0;
		}
		
		if($flag==0){
			$information = "insert into stock_log (site, sku, info, info_stock, order_id, product_name, unit_price, print_msg, total_amount, add_time) values (\"". $arr["site"] ."\", \"". $k ."\",\"" . addslashes(json_encode($v['sizeNum']))."\", \"".$arr['flag']."\", \"".$arr['order_id']."\", \"".$v['productName']."\", \"".$v['unitPrice']."\", \"".$v['printMesg']."\", \"".$v['totalAmount']."\", \"".date('Y-m-d H:i:s', time())."\")";
			$zendlog->log($information, Zend_Log::INFO);//错误记录
		}
	}else{
		//向数据库更新网站订单数据
		$res = mysql_query("update stock_log set info_stock=\"". $arr['flag'] ."\" where order_id=\"". $arr['order_id'] ."\" and site=\"". $arr["site"] ."\"");
		if (!$res) {
			$flag = 0;
		}
		
		if($flag==0){
			$information = "update stock_log (site, sku, info, info_stock, order_id, product_name, unit_price, print_msg, total_amount, add_time) values (\"". $arr["site"] ."\", \"". $k ."\",\"" . addslashes(json_encode($v['sizeNum']))."\", \"".$arr['flag']."\", \"".$arr['order_id']."\", \"".$v['productName']."\", \"".$v['unitPrice']."\", \"".$v['printMesg']."\", \"".$v['totalAmount']."\", \"".date('Y-m-d H:i:s', time())."\")";
			$zendlog->log($information, Zend_Log::INFO);//错误记录
		}
	}
}

//若是非退货则向数据库插入order_log，buyer信息，否则只需更新网站订单
if($arr['flag'] == 'sub'){
	$flag = 1;
	if($check!==false){
		$res1 = mysql_query("update order_log set flag=\"". $arr['flag'] ."\" where order_id=\"". $arr['order_id'] ."\" and site=\"". $arr["site"] ."\"");
	}else{
		$res1 = mysql_query("insert into order_log (order_id, site, flag, remark, total_amount, ship_company, yunfei, add_time) values (\"". $arr['order_id'] ."\", \"". $arr['site'] ."\",\"" . $arr['flag'] ."\", \"".$arr['data']['remark']."\", \"".$arr['data']['orderTotalAmount']."\", \"".$arr['data']['shipCompany']."\", \"".$arr['data']['yunfei']."\", \"".date('Y-m-d H:i:s', time())."\")");
	}
	
	if(!$res1){
		$flag = 0;
		$information = "insert into order_log (order_id, site, flag, remark, total_amount, ship_company, yunfei, add_time) values (\"". $arr['order_id'] ."\", \"". $arr['site'] ."\",\"" . $arr['flag'] ."\", \"".$arr['data']['remark']."\", \"".$arr['data']['orderTotalAmount']."\", \"".$arr['data']['shipCompany']."\", \"".$arr['data']['yunfei']."\", \"".date('Y-m-d H:i:s', time())."\")";
		$zendlog->log($information, Zend_Log::INFO);//错误记录
	}else{
		$query="SELECT LAST_INSERT_ID()";
		$result=mysql_query($query);
		$rows=mysql_fetch_row($result);
		if($check==false){
			$res2 = $res1 = mysql_query("insert into buyer (order_id, site, order_log_id, name, contact_name, address, country, city, state, post_code, phone, facebook, twitter) values (\"". $arr['order_id'] ."\", \"". $arr['site'] ."\",\"" . $rows[0] ."\", \"".$arr['data']['shipAddress']['buyer']."\", \"".$arr['data']['shipAddress']['contactName']."\", \"".$arr['data']['shipAddress']['contactAddress']."\", \"".$arr['data']['shipAddress']['country']."\", \"".$arr['data']['shipAddress']['city']."\", \"".$arr['data']['shipAddress']['state']."\", \"".$arr['data']['shipAddress']['postCode']."\", \"".$arr['data']['shipAddress']['phone']."\", \"".$arr['data']['shipAddress']['Facebook']."\", \"".$arr['data']['shipAddress']['Twitter']."\")");
			if(!$res2){
				$flag = 0;
				$information = "insert into buyer (order_id, site, order_log_id, name, contact_name, address, country, city, state, post_code, phone, facebook, twitter) values (\"". $arr['order_id'] ."\", \"". $arr['site'] ."\",\"" . $rows[0] ."\", \"".$arr['data']['shipAddress']['buyer']."\", \"".$arr['data']['shipAddress']['contactName']."\", \"".$arr['data']['shipAddress']['contactAddress']."\", \"".$arr['data']['shipAddress']['country']."\", \"".$arr['data']['shipAddress']['city']."\", \"".$arr['data']['shipAddress']['state']."\", \"".$arr['data']['shipAddress']['postCode']."\", \"".$arr['data']['shipAddress']['phone']."\", \"".$arr['data']['shipAddress']['Facebook']."\", \"".$arr['data']['shipAddress']['Twitter']."\")";
				$zendlog->log($information, Zend_Log::INFO);//错误记录
			}
		}
	}
}else{
	//向数据库更新网站订单数据
	$res = mysql_query("update order_log set flag=\"". $arr['flag'] ."\" where order_id=\"". $arr['order_id'] ."\" and site=\"". $arr["site"] ."\"");
	if (!$res) {
		$flag = 0;
	}
	
	if($flag==0){
		$information = "update order_log set flag=\"". $arr['flag'] ."\" where order_id=\"". $arr['order_id'] ."\" and site=\"". $arr["site"] ."\"";
		$zendlog->log($information, Zend_Log::INFO);//错误记录
	}
}

if ($flag) {	
	mysql_query("COMMIT");
	echo 1;
} else {
	mysql_query("ROOLBACK");
	echo 0;
}
